import store from '../store'
import Q from 'q'

export const hideFilter = () => {
  store.commit('HIDE_COVER')
}

export const loadTeamsOptions = (args, teamOptionSetting) => {

  return Q.Promise((success, error) => {
    args = Object.assign({source: 'webapp'}, args)
    store.dispatch('getTeams', args)
    .then((response) => {
      if(response.data.errcode === 0) {
        let teamOptions =  []
        if(typeof response.data.results.teams !== 'undefined') {
          let teams = response.data.results.teams
          teams.forEach((elem, index) => {
            teamOptions.push({
              value:elem.id,
              text:elem.team_name
            })
          })
        }
        success(teamOptions)
      } else {
        error(response)
      }
    })
    .catch((e) => {
      error(e)
    })
  }).catch((e) => {
    console.log('获取团队失败')
  })
}

export const exists = (options1, value, ID) => {

  let IDs = []
  options1.forEach((elem1) => {
    IDs.push(elem1[ID])
  })

  return IDs.indexOf(value) > -1
}

export const mergetOptions = (options1, options2, ID) => {
  let IDs = []
  let freshOptions = []

  options1.forEach((elem1) => {
    IDs.push(elem1[ID])
  })

  options2.forEach((elem2) => {
    if (IDs.indexOf(elem2[ID]) === -1) {
      freshOptions.push(elem2)
    }
  })
  console.debug('IDs', IDs)
  console.debug('IDs', IDs)
  return options1.concat(freshOptions)
}

export const filterUserFromTeam = (teams) => {
  let temps = []
  teams.forEach(function (team, index) {
    team.team_members.forEach(function (member, mindex) {
      member.team_name = team.team_name
      temps.push(member)
    })

    team.team_managers.forEach(function (member, mindex) {
      member.team_name = team.team_name
      temps.push(member)
    })
  })

  // console.log('this.teamsMembers', JSON.stringify(temps));

  return temps
}

export const loadTeamSettings = (Args, TeamSettings) => {
  Args = Object.assign({ page_size: 100, page_index: 1, is_own: 1 }, Args)

  store.commit('UPDATE_TOPFILTER_LOADING', true)

  TeamSettings = Object.assign(TeamSettings || {}, store.state.app.filterOptions[1]['options'][2])
  return Q.Promise((success, error) => {
    loadTeamsOptions(Args).then((teamOptions) => {
      if (typeof teamOptions.length === 'undefined' || !teamOptions.length) success(false)

      if (typeof TeamSettings.options !== 'undefined') {
        TeamSettings.options = mergetOptions(TeamSettings.options, teamOptions, 'value')
      } else {
        TeamSettings.options = teamOptions
      }

      if (typeof TeamSettings.checked !== 'undefined' || !exists(TeamSettings.options, TeamSettings.checked, 'value')) {
        if (TeamSettings.options.length) {
          TeamSettings.checked = TeamSettings.options[0].value
        }
      }

      let filterOptions = store.state.app.filterOptions
      filterOptions[1]['options'][2] = TeamSettings

      store.commit('UPDATE_FILTER_OPTIONS', filterOptions)
      store.commit('UPDATE_TOPFILTER_LOADING', false)

      success([filterOptions, TeamSettings])
    }).catch((e) => {
      store.commit('UPDATE_TOPFILTER_LOADING', false)
      console.error(e)
    })
  }).catch((e) => {
    store.commit('UPDATE_TOPFILTER_LOADING', false)
    console.error(e)
  })
}

export const loadMembersOptions = (args, memberOptionSetting) => {
  return Q.Promise((success, error) => {
    args = Object.assign({source: 'webapp'}, args)
    store.dispatch('getTeams', args)
    .then((response) => {
      if (response.data.errcode === 0) {
        let memberOptions = []
        if (typeof response.data.results.teams !== 'undefined') {
          let ids = []
          let members = filterUserFromTeam(response.data.results.teams)
          members.forEach((elem, index) => {
            if (ids.indexOf(elem.suid) === -1) {
              ids.push(elem.suid)
              memberOptions.push({
                value: elem.suid,
                text: elem.name
              })
            }
          })
          // console.log(JSON.stringify(members))
        }
        success(memberOptions)
      } else {
        error(response)
      }
    })
    .catch((e) => {
      error(e)
    })
  }).catch((e) => {
    console.log('获取团队失败')
  })
}

export const loadMemberSettings = (Args, MemberSettings) => {
  Args = Object.assign({page_size: 100, page_index: 1, is_own: 1}, Args)
  store.commit('UPDATE_TOPFILTER_LOADING', true)

  if (!MemberSettings) MemberSettings = store.state.app.filterOptions[1]['options'][1]

  return Q.Promise((success, error) => {
    loadMembersOptions(Args).then((memberOptions) => {
      if (typeof memberOptions.length === 'undefined' || !memberOptions.length) success(false)
      // console.debug('memberOptions', JSON.stringify(memberOptions))
      if (typeof MemberSettings.options !== 'undefined') {
        MemberSettings.options = mergetOptions(MemberSettings.options, memberOptions, 'value')
      } else {
        MemberSettings.options = memberOptions
      }

      if (typeof MemberSettings.checked !== 'undefined' ||
        !exists(MemberSettings.options, MemberSettings.checked, 'value')) {
        if (MemberSettings.options.length) {
          MemberSettings.checked = MemberSettings.options[0].value
        }
      }

      let filterOptions = store.state.app.filterOptions
      filterOptions[1]['options'][1] = MemberSettings

      store.commit('UPDATE_FILTER_OPTIONS', filterOptions)
      store.commit('UPDATE_TOPFILTER_LOADING', false)

      success([filterOptions, MemberSettings])
    }).catch((e) => {
      store.commit('UPDATE_TOPFILTER_LOADING', false)
      console.error(e)
    })
  }).catch((e) => {
    store.commit('UPDATE_TOPFILTER_LOADING', false)
    console.error(e)
  })
}

export const loadFilterFunc = (options) => {
  let secElem = options[1]
  if (secElem.name === 'teamId' || secElem.name === 'team_id') {
    if (typeof this.filterTeamIndex === 'undefined') this.filterTeamIndex = 1
    this.filterTeamIndex ++
    loadTeamSettings({ page_index: this.filterTeamIndex })
    .then((options) => {
      if (options === false) {
        this.filterTeamIndex = 1
        return this.filterTeamIndex
      }
        // this.filterOptions = []
      this.filterActiveItem = []
      setTimeout(() => {
        this.filterActiveItem = options[1]
      })
    })
  } else if (secElem.name === 'suid') {
    if (typeof this.filterMemberIndex === 'undefined') this.filterMemberIndex = 1
    this.filterMemberIndex ++
    loadMemberSettings({page_index: this.filterMemberIndex})
    .then((options) => {
      if (options === false) {
        this.filterMemberIndex = 1
        return this.filterMemberIndex
      }
        // this.filterOptions = []
      this.filterActiveItem = []
      setTimeout(() => {
        this.filterActiveItem = options[1]
      })
    })
  }
}
